package com.lubase.dingding.service;

import com.alibaba.fastjson.JSONObject;
import com.lubase.core.model.SelectUserModel;
import com.lubase.core.model.UserInfoModel;
import com.lubase.core.service.UserInfoService;
import com.lubase.core.service.userright.UserRightService;
import com.lubase.orm.exception.WarnCommonException;
import com.lubase.orm.model.LoginUser;
import com.lubase.orm.service.IDGenerator;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class DingTalk2LubaseService {
    @Value("${dingding.appkey}")
    String appKey;

    @Value("${dingding.appsecret}")
    String appSecret;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    UserRightService userRightService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    IDGenerator idGenerator;

    @Autowired
    DingProcessService dingProcessService;

    public String getAccessToken() {
        JSONObject jsonObject = restTemplate.getForObject("https://oapi.dingtalk.com/gettoken?appkey=" + appKey + "&appsecret=" + appSecret, JSONObject.class);
        if (jsonObject != null && jsonObject.containsKey("access_token")) {
            return jsonObject.get("access_token").toString();
        } else {
            return null;
        }
    }

    public SelectUserModel getUserInfoByAuthCode(@NonNull String authCode) {
        SelectUserModel userModel = null;
        String url = String.format("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=%s", getAccessToken());
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("code", authCode);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, String>> formEntity = new HttpEntity<>(map, headers);
        JSONObject jsonObject = restTemplate.postForObject(url, formEntity, JSONObject.class);

        log.info("getUserInfoByAuthCode: " + jsonObject);

        if (jsonObject != null && jsonObject.containsKey("result")) {
            JSONObject result = jsonObject.getJSONObject("result");
            userModel = new SelectUserModel();
            userModel.setUserCode(result.get("userid").toString());
            userModel.setUserName(result.get("name").toString());
            userModel.setDeptId("0");
            userModel.setId(String.valueOf(idGenerator.nextId()));
            userModel.setDeptName("dingtalk");
        }
        return userModel;
    }

    @SneakyThrows
    public LoginUser getSSOUser(String authCode) {
        if (StringUtils.isEmpty(authCode)) {
            return null;
        }
        // 根据token获取用户信息
        SelectUserModel userModel = getUserInfoByAuthCode(authCode);
        if (userModel == null) {
            return null;
        }
        // 根据工号获取lubase系统欸用户信息
        UserInfoModel userInfoModel = userInfoService.getUserInfo(userModel.getUserCode());
        if (userInfoModel == null) {
            // 如果用户不存在，则创建用户
            List<SelectUserModel> list = new ArrayList<>();
            list.add(userModel);
            // 创建用户
            userInfoService.createUser(list);
            // 创建用户再次获取用户信息
            userInfoModel = userInfoService.getUserInfo(userModel.getUserCode());
            if (userInfoModel == null) {
                throw new WarnCommonException("获取用户信息异常，请重试");
            }
        }
        if (!userInfoModel.isEnableTag()) {
            throw new WarnCommonException("账号已经被禁用，请联系管理员");
        }
        LoginUser user = new LoginUser();
        user.setId(userInfoModel.getId());
        user.setCode(userInfoModel.getUserCode());
        user.setName(userInfoModel.getUserName());

        // 设置用户权限，并创建系统内token
        this.userRightService.getUserRight(user.getId());
        user.setToken(userInfoService.createUserToken(user));
        //获取七宝token
        user.setSsoToken(dingProcessService.getTokenFromQibao(userModel.getDeptName(),user.getToken()));
        return user;
    }
}
